<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Stat as StatModel;
use app\wh\model\Color as ColorModel;
use app\wh\model\StockType as StockTypeModel;
use think\Db;

/**
 * 库存模型
 */
class Stock extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'wh_stock';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 获取物料条形码
     * @param array $goods 物料信息
     * @param bool $add_sn true：新增库存 false：仅查询
     * @return mixed|string
     */
    public static function getStockSn($goods = [],$add_sn = true){

        $goods['title'] = !empty($goods['material_name'])?$goods['material_name']:$goods['title'];
        if(!empty($goods['supplier_color']))$goods['model'] = $goods['supplier_color'];
        $where = [
            ['supplier_id','=',$goods['supplier_id']],
            ['type_pid','=',$goods['type_pid']],
            ['type_id','=',$goods['type_id']],
            ['model','=',$goods['model']],
        ];
        if(!empty($goods['model2']))$where[] = ['model2','=',$goods['model2']];//铝卷，批号
        if(!empty($goods['edit_stock_id']))$where[] = ['id','=',$goods['edit_stock_id']];//物料ID
        if(!empty($goods['is_where']))return $where;//直接返回查询条件
        $stock_sn = Db::name('wh_stock')->where($where)->value('stock_sn');

        $add = [
            'supplier_id'           =>  $goods['supplier_id'],
            'type_pid'              =>  $goods['type_pid'],
            'type_id'               =>  $goods['type_id'],
            'title'                 =>  $goods['title'],
            'model'                 =>  $goods['model'],
            'create_time'           =>  time(),
        ];
        if(!empty($goods['supplier_color']))$add['supplier_color'] = $goods['supplier_color'];
        if(!empty($goods['color_type_id']))$add['color_type_id'] = $goods['color_type_id'];
        if(!empty($goods['color_id']))$add['color_id'] = $goods['color_id'];
        if(!empty($goods['color_sn']))$add['color_sn'] = $goods['color_sn'];
        if(!empty($goods['heat']))$add['heat'] = $goods['heat'];
        if(!empty($goods['long']))$add['long'] = $goods['long'];
        if(!empty($goods['high']))$add['high'] = $goods['high'];
        if(!empty($goods['quality']))$add['quality'] = $goods['quality'];
        if(!empty($goods['lot_sn']))$add['lot_sn'] = $goods['lot_sn'];
        if(!empty($goods['num']))$add['num'] = $goods['num'];
        if(!empty($goods['model2']))$add['model2'] = $goods['model2'];
        if(!empty($goods['type_id2']))$add['type_id2'] = $goods['type_id2'];
        if(!empty($goods['type_id3']))$add['type_id3'] = $goods['type_id3'];

        //新增库存
        if(empty($stock_sn) && $add_sn){

            $stock_sn = self::stockSn();
            $add['stock_sn'] = $stock_sn;

            Db::name('wh_stock')->insertGetId($add);
        }

        return $stock_sn;
    }

    //设置物料条形码
    public static function stockSn(){

        $stock_sn = Db::name('wh_stock')->order('id desc')->value('id');
        $stock_sn = intval($stock_sn)+1;

        return date('ym').sprintf ("%04d", $stock_sn);
    }

    //设置领用退还编号
    public static function useSn(){

        $use_sn = Db::name('wh_stock_use_log')->order('use_sn desc')->value('use_sn');
        preg_match('/\d+/',$use_sn,$arr);
        $arr[0] = empty($arr[0])?0:$arr[0];
        $use_sn = intval($arr[0])+1;

        return "USE".sprintf ("%06d", $use_sn);
    }

    //获取库存
    public static function getSumNumber($data = []){

        if(!empty($data['stock_sn']))$input['stock_sn'] = $data['stock_sn'];
        if(!empty($data['supplier_id']))$input['supplier_id'] = $data['supplier_id'];
        if(!empty($data['type_pid']))$input['type_pid'] = $data['type_pid'];
        if(!empty($data['type_id']))$input['type_id'] = $data['type_id'];
        if(!empty($data['type_id2']))$input['type_id2'] = $data['type_id2'];
        if(!empty($data['type_id3']))$input['type_id3'] = $data['type_id3'];
        if(!empty($data['model']))$input['model'] = $data['model'];
        //if(!empty($data['color_id']))$input['color_id'] = $data['color_id'];

        $where = [];
        if(!empty($input)){
            foreach ($input as $k=>$v){
                $where[] = [$k,'=',$v];
            }
        }

        if(!empty($where))$num = Db::name('wh_stock')->where($where)->value('number');
        if(empty($num))$num = '暂无库存';

        return $num;
    }

    //获取库存损耗
    public static function getLossNumber($data = []){

        $input['stock_sn'] = empty($data['stock_sn'])?'':$data['stock_sn'];
        //$input['supplier_id'] = empty($data['supplier_id'])?'':$data['supplier_id'];
        //$input['type_pid'] = empty($data['type_pid'])?'':$data['type_pid'];
        //$input['type_id'] = empty($data['type_id'])?'':$data['type_id'];
        //$input['model'] = empty($data['stock_sn'])?'':$data['model'];

        $where = [];
        if(!empty($input)){
            foreach ($input as $k=>$v){
                $where[] = [$k,'=',$v];
            }
        }

        $num = Db::name('wh_stock_take_log')->where($where)->sum('loss_number');

        return $num;
    }

    /**
     * 出入库记录
     * @param int $type 0:入库 1:出库
     * @param array $data 库存信息
     * @param int $number 出入库数量
     * @param string $uid 操作人UID
     * @param bool $is_update true：更新库存   false：不更新库存，仅做记录
     * @return array
     */
    public static function log($type = 0,$data = [],$number = 0,$uid = '',$is_update = true){

        $re = ['msg'=>''];
        if(empty($data['stock_sn']))$re['msg'] = '请输入库存编码';
        if(empty($number))$re['msg'] = '请输入数量';
        if($number<0)$re['msg'] = '请输入有效数量';
        //检查库存数量
        $in_number = Db::name('wh_stock')->where(['stock_sn'=>$data['stock_sn']])->value('number');
        if($type == 1 && round($number,2) > round($in_number,2))$re['msg'] = '库存不足';
        if($re['msg'])return $re;


        $add = [
            'status'            =>  $type,
            'number'            =>  $number,
            'uid'               =>  $uid,
            'create_time'       =>  time(),
        ];

        if(!empty($data['material_sn'])){
            $add['cate'] = 1;//1采购单入库，2领用，3退还
            $add['material_sn'] = $data['material_sn'];
        }
        if(!empty($data['stock_sn']))$add['stock_sn'] = $data['stock_sn'];
        if(!empty($data['material_id']))$add['material_id'] = $data['material_id'];
        if(!empty($data['order_id']))$add['order_id'] = $data['order_id'];
        if(!empty($data['archives_sn']))$add['archives_sn'] = $data['archives_sn'];
        if(!empty($data['supplier_id']))$add['supplier_id'] = $data['supplier_id'];
        if(!empty($data['type_pid']))$add['type_pid'] = $data['type_pid'];
        if(!empty($data['type_id']))$add['type_id'] = $data['type_id'];
        if(!empty($data['type_id2']))$add['type_id2'] = $data['type_id2'];
        if(!empty($data['type_id3']))$add['type_id3'] = $data['type_id3'];
        if(!empty($data['goods_id']))$add['goods_id'] = $data['goods_id'];
        if(!empty($data['model']))$add['model'] = $data['model'];
        if(!empty($data['quality']))$add['quality'] = $data['quality'];
        if(!empty($data['lot_sn']))$add['lot_sn'] = $data['lot_sn'];
        if(!empty($data['note']))$add['note'] = $data['note'];
        if(!empty($data['note2']))$add['note2'] = $data['note2'];
        if(!empty($data['cate']))$add['cate'] = $data['cate'];
        if(!empty($data['use_sn']))$add['use_sn'] = $data['use_sn'];
        if(!empty($data['num']))$add['num'] = $data['num'];

        //入库，且采购单号存在，则更新采购单信息
        if($type == 0 && !empty($add['material_sn'])){
            //更新采购单明细状态，入库完成
            Db::name('wh_material_goods')->where(['material_sn'=>$add['material_sn'],'stock_sn'=>$data['stock_sn']])->update(['status'=>3]);

            //更新采购单状态，入库完成
            $material_status = Db::name('wh_material_goods')->where(['material_sn'=>$add['material_sn'],'status'=>3])->count();
            $material_status2 = Db::name('wh_material_goods')->where(['material_sn'=>$add['material_sn']])->count();
            if($material_status == $material_status2)Db::name('wh_material')->where(['material_sn'=>$add['material_sn']])->update(['status'=>3]);
            //更新采购单状态，入库中
            else Db::name('wh_material')->where(['material_sn'=>$add['material_sn']])->update(['status'=>2]);
        }
        //更新日志
        $re['log_id'] = Db::name('wh_stock_log')->insertGetId($add);
        //更新库存
        if($is_update)self::upStockNumber($type,$add['stock_sn'],$number);

        return $re;
    }

    /**
     * 盘存记录
     * @param int $type 0:入库 1:出库
     * @param array $data 库存信息
     * @param int $number 盘存数量
     * @param string $uid 操作人UID
     * @return array
     */
    public static function takeLog($type = 0,$data = [],$number = 0,$uid = ''){

        $re = ['msg'=>''];
        if(empty($data['stock_sn']))$re['msg'] = '请输入库存编码';
        //if(empty($number))$re['msg'] = '请输入数量';
        if($number<0)$re['msg'] = '请输入有效数量';
        if($re['msg'])return $re;

        $loss_number = $number-$data['number'];
        if($data['number']<0)$loss_number = $number-$data['number'];
        $add = [
            'stock_sn'          =>  $data['stock_sn'],
            'old_number'        =>  $data['number'],
            'number'            =>  $number,
            'loss_number'       =>  $loss_number,
            'uid'               =>  $uid,
            'create_time'       =>  time(),
        ];

        if(!empty($data['supplier_id']))$add['supplier_id'] = $data['supplier_id'];
        if(!empty($data['type_pid']))$add['type_pid'] = $data['type_pid'];
        if(!empty($data['type_id']))$add['type_id'] = $data['type_id'];
        if(!empty($data['type_id2']))$add['type_id2'] = $data['type_id2'];
        if(!empty($data['type_id3']))$add['type_id3'] = $data['type_id3'];
        if(!empty($data['model']))$add['model'] = $data['model'];

        //更新日志
        $re['log_id'] = Db::name('wh_stock_take_log')->insertGetId($add);
        //更新库存
        self::upStockNumber($type,$add['stock_sn'],$number);

        return $re;
    }

    /**
     * 领用退还记录
     * @param int $type 0:退还 1:领用
     * @param array $data 库存信息
     * @param string $uid 操作人UID
     * @return array
     */
    public static function useLog($type = 0,$data = [],$uid = ''){

        //物料信息
        $stock = Db::name('wh_stock')->where(['stock_sn'=>$data['stock_sn']])->find();

        //无物料编码(stock_sn)，order_id=0的就是后台手动录入覆盖率，同时也是领用退还记录
        $re = ['msg'=>''];

        $useSn = !empty($data['use_sn'])?$data['use_sn']:self::useSn();//领用编号

        $number = $data['post_number'];
        //领用
        if($type == 1){
            foreach ($data['list'] as $v){

                if(!empty($v['use_sn']))$useSn = $v['use_sn'];
                $order = Db::name('mill_order')->where(['archives_sn'=>$v['archives_sn']])->find();
                $order_color_id = Db::name('wh_order_color')->where([['order_id','=',$order['id']],['stock_sn','=',$stock['stock_sn']]])->value('id');

                //查询是否有记录
                $where = [
                    ['stock_sn','=',$stock['stock_sn']],
                    ['archives_sn','=',$v['archives_sn']],
                ];
                $log = Db::name('wh_stock_use_log')->where($where)->find();
                //新增
                if(empty($log)){
                    $add = [
                        'use_sn'            =>  $useSn,
                        'number'            =>  $v['post_number'],
                        'uid'               =>  $uid,
                        'create_time'       =>  time(),

                        'order_id'          =>  $order['id'],
                        'archives_sn'       =>  $order['archives_sn'],
                        'engineering'       =>  $order['engineering'],
                        'order_color_id'    =>  $order_color_id,

                        'stock_id'          =>  $stock['id'],
                        'stock_sn'          =>  $stock['stock_sn'],
                    ];

                    if(!empty($stock['supplier_id']))$add['supplier_id'] = $stock['supplier_id'];
                    if(!empty($stock['type_pid']))$add['type_pid'] = $stock['type_pid'];
                    if(!empty($stock['type_id']))$add['type_id'] = $stock['type_id'];
                    if(!empty($stock['type_id2']))$add['type_id2'] = $stock['type_id2'];
                    if(!empty($stock['type_id3']))$add['type_id3'] = $stock['type_id3'];
                    if(!empty($stock['model']))$add['model'] = $stock['model'];

                    if(!empty($v['log_id']))$add['log_id'] = $v['log_id'];

                    Db::name('wh_stock_use_log')->insertGetId($add);
                }
                //更新
                else {
                    $add = ['use_sn'=>$useSn,'create_time'=>time()];
                    if(!empty($v['log_id']))$add['log_id'] = $v['log_id'];

                    Db::name('wh_stock_use_log')->where(['id'=>$log['id']])->setInc('number',$v['post_number']);
                    Db::name('wh_stock_use_log')->where(['id'=>$log['id']])->update($add);
                }

            }
        }
        //退还
        else{
            foreach ($data['list'] as $v){

                //查询是否有记录
                $where = [
                    ['id','=',$v['id']],
                ];
                $log = Db::name('wh_stock_use_log')->where($where)->find();
                //更新
                if(!empty($log)){
                    Db::name('wh_stock_use_log')->where(['id'=>$log['id']])->setInc('back_number',$v['post_number']);
                    if(!empty($v['log_id_back']))Db::name('wh_stock_use_log')->where(['id'=>$log['id']])->update(['log_id_back'=>$v['log_id_back']]);
                }
                //将退还数量更新到领用记录里面去
                if(!empty($log['log_id']))Db::name('wh_stock_log')->where(['id'=>$log['log_id']])->update(['back_number'=>$v['post_number']]);
            }
        }

        return $re;
    }
    public static function useLog_old($type = 0,$list = [],$uid = ''){

        $re = ['msg'=>''];

        $useSn = self::useSn();//领用编号
        foreach ($list as $data){
            $number = $data['post_number'];
            //领用
            if($type == 1){
                $archives_sn_arr = explode(',',$data['archives_sn']);
                $row_area = Db::name('mill_order_archives')->where([['archives_sn','in',$data['archives_sn']]])->sum('row_area');
                //遍历工程
                $i = 1;
                $count = count($archives_sn_arr);
                foreach ($archives_sn_arr as $archives_sn){

                    $archives = Db::name('mill_order_archives')->field('order_id,archives_sn,sum(row_area) as row_area,sum(number) as number')->where(['archives_sn'=>$archives_sn])->find();
                    //分配到的数量
                    $area__number = $number;
                    //如果不是最后一个物料，则继续分配数量和比例
                    if($i != $count){
                        //面积比例
                        $area_scale = round(($archives['row_area']/$row_area),2);
                        //分配到的数量
                        $area__number = round(($number*$area_scale),2);
                        //总数量-分配到的数量
                        $number -= $area__number;
                    }

                    //查询是否有记录
                    $where = [
                        ['stock_sn','=',$data['stock_sn']],
                        ['order_id','=',$archives['order_id']],
                    ];
                    $log = Db::name('wh_stock_use_log')->where($where)->find();
                    //新增
                    if(empty($log)){
                        $add = [
                            'use_sn'            =>  $useSn,
                            'number'            =>  $area__number,
                            'uid'               =>  $uid,
                            'create_time'       =>  time(),

                            'order_id'          =>  $archives['order_id'],
                            'archives_sn'       =>  $archives['archives_sn'],

                            'stock_sn'          =>  $data['stock_sn'],
                        ];

                        if(!empty($data['supplier_id']))$add['supplier_id'] = $data['supplier_id'];
                        if(!empty($data['type_pid']))$add['type_pid'] = $data['type_pid'];
                        if(!empty($data['type_id']))$add['type_id'] = $data['type_id'];
                        if(!empty($data['model']))$add['model'] = $data['model'];

                        Db::name('wh_stock_use_log')->insertGetId($add);
                    }
                    //更新
                    else Db::name('wh_stock_use_log')->where(['id'=>$log['id']])->setInc('number',$area__number);

                    $i++;
                }
            }
            //退还
            else{
                $use_sn_arr = Db::name('wh_stock_use_log')->where([['archives_sn','in',$data['archives_sn']],['stock_sn','in',$data['stock_sn']]])->column('DISTINCT use_sn');
                //遍历领用编号
                foreach ($use_sn_arr as $use_sn){

                    $archives_sn_arr = Db::name('wh_stock_use_log')->where(['use_sn'=>$use_sn,'stock_sn'=>$data['stock_sn']])->column('DISTINCT archives_sn');
                    $row_area = Db::name('mill_order_archives')->where([['archives_sn','in',implode(',',$archives_sn_arr)]])->sum('row_area');
                    //遍历工程
                    $i = 1;
                    $count = count($archives_sn_arr);
                    foreach ($archives_sn_arr as $archives_sn){

                        $archives = Db::name('mill_order_archives')->field('order_id,sum(row_area) as row_area,sum(number) as number')->where(['archives_sn'=>$archives_sn])->find();
                        //分配到的数量
                        $area__number = $number;
                        //如果不是最后一个物料，则继续分配数量和比例
                        if($i != $count){
                            //面积比例
                            $area_scale = round(($archives['row_area']/$row_area),2);
                            //分配到的数量
                            $area__number = round(($number*$area_scale),2);
                            //总数量-分配到的数量
                            $number -= $area__number;
                        }

                        //查询是否有记录
                        $where = [
                            ['use_sn','=',$use_sn],
                            ['stock_sn','=',$data['stock_sn']],
                            ['order_id','=',$archives['order_id']],
                        ];
                        $log = Db::name('wh_stock_use_log')->where($where)->find();
                        //更新
                        if(!empty($log))Db::name('wh_stock_use_log')->where(['id'=>$log['id']])->setInc('back_number',$area__number);

                        $i++;
                    }

                }
            }
        }

        return $re;
    }

    /**
     * 更新库存
     * @param int $type 0:入库 1:出库 2:直接更新库存最终数量
     * @param string $stock_sn 库存编码
     * @param int $number 出入库数量
     * @return array
     */
    public static function upStockNumber($type = 0,$stock_sn = '',$number = 0){

        //入库
        if($type == 0){
            //更新库存
            Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->setInc('number',$number);
            Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->setInc('join_number',$number);
        }
        //出库
        elseif($type == 1){
            //更新库存
            Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->setDec('number',$number);
            Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->setInc('out_number',$number);
        }
        //直接更新库存最终数量
        elseif($type == 2){
            //更新库存
            Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->update(['number'=>$number]);
        }
        //更新库存批号
        Db::name('wh_stock')->where(['stock_sn'=>$stock_sn,'number'=>0])->update(['lot_sn'=>'','model2'=>'']);
    }

    /**
     * 同步新增同规格不同物料类别的库存
     * @param string $stock_sn 物料编码
     * @param array $old_stock 更新前的物料信息
     * @return array
     */
    public static function addSameStock($stock_sn = '',$old_stock = []){

        $stock = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
        if(empty($stock))return '';
        //目前仅限稀油面漆和油漆面漆的同步新增

        //判断油漆库类型是否关联稀油库
        $link_type_ids = StockTypeModel::getLinkTypeIds($stock);
        if(empty($link_type_ids['level1']))return '';

        //关联的稀油库分类
        $stock['type_pid'] = $link_type_ids['level1'];
        $stock['type_id'] = $link_type_ids['level2'];
        $stock['type_id2'] = !empty($link_type_ids['level3'])?$link_type_ids['level3']:0;
        $stock['type_id3'] = !empty($link_type_ids['level4'])?$link_type_ids['level4']:0;

        //先获取更新前的物料信息，是否有相同的物料信息
        $stock_sn = '';
        if(!empty($old_stock)){
            //判断油漆库类型是否关联稀油库
            $link_type_ids = StockTypeModel::getLinkTypeIds($old_stock);
            if(!empty($link_type_ids['level1'])){
                $old_stock['type_pid'] = $link_type_ids['level1'];
                $old_stock['type_id'] = $link_type_ids['level2'];
                $old_stock['type_id2'] = !empty($link_type_ids['level3'])?$link_type_ids['level3']:0;
                $old_stock['type_id3'] = !empty($link_type_ids['level4'])?$link_type_ids['level4']:0;
                $stock_sn = self::getStockSn($old_stock,false);
            }

        }
        //无相同的物料信息，则获取更新后的物料信息
        if(empty($stock_sn))$stock_sn = self::getStockSn($stock,false);
        //如果已有相同的物料信息，则同步更新
        //同步更新同规格不同物料类别的物料信息
        if(!empty($stock_sn)){
            $stock2 = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
            //更新物料信息
            $update = [
                'supplier_id'       =>  $stock['supplier_id'],
                'type_pid'          =>  $stock['type_pid'],
                'type_id'           =>  $stock['type_id'],
                'type_id2'          =>  $stock['type_id2'],
                'type_id3'          =>  $stock['type_id3'],
                'heat'              =>  $stock['heat'],
                'color_type_id'     =>  $stock['color_type_id'],
            ];
            $update2 = $update;
            $update2['supplier_color'] = $stock['supplier_color'];
            $update2['model'] = $stock['model'];
            $update2['title'] = $stock['title'];
            $update2['long'] = $stock['long'];
            $update2['high'] = $stock['high'];
            $update2['quality'] = $stock['quality'];
            $update2['model2'] = $stock['model2'];
            //如果更换了物料类型，则自编码也根据物料类型进行更新
            if($stock2['type_id'] != $update['type_id'])$update2['color_sn'] = ColorModel::getColorSn($update['type_id'],$update['heat']);
            Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->update($update2);

            //更新厂家色号
            $update3 = $update;
            $update3['supplier_color'] = $stock['model'];
            $update3['color'] = $stock['title'];
            Db::name('wh_order_color')->where(['stock_sn'=>$stock_sn])->update($update3);
        }
        else{
            //同步新增同规格不同物料类别的物料信息
            //如果是新增，则重置自编码
            $stock['color_sn'] = ColorModel::getColorSn($stock['type_id'],$stock['heat']);
            $stock_sn = self::getStockSn($stock);
        }

        return $stock_sn;
    }

    // 头部统计
    public static function topStatHtml($arr = []){

        $option = "{
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '15',
                            right: '15',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        yAxis : [
                            {
                                type : 'value',
                                axisLabel : {
                                    formatter: ''
                                }
                            }
                        ],
                        xAxis: {
                            type: 'category',
                            boundaryGap : false,
                            data: [
                                '油漆(KG)',
                                '粉末(KG)',
                                '木纹(KG)',
                                '色浆(KG)',
                                '铝卷(KG)',
                                '铝板(KG)',
                                '型材(KG)',
                                '化工(KG)',
                                '生产物资',
                                '办公物资',
                            ]
                        },
                        series: [
                          {
                            'name': '总量',
                            'type': 'line',
                            'smooth':true,
                            'data': [
                              150,
                              100,
                              200,
                              140,
                              100,
                              230,
                              138,
                              201,
                              124,
                              116,
                            ],
                            'itemStyle': {
                              'normal': {
                                'label': {
                                  'show': true
                                }
                              }
                            }
                          },
                        ]
                    }";
        $url = url('mill/stat/ajaxClient');
        $top_html = StatModel::materialHtml($url,$option,['charts']);

        return $top_html;
    }

    // 统计库存信息
    public static function getOneStat($val = null,$field = 'stock_sn',$condition = 'eq',$map = [],$time = []){
        $where[] = [$field,$condition,$val];
        if(!empty($map))$where = $map;
        if(empty($time[0]))$time[0] = 0;
        if(empty($time[1]))$time[1] = time();
        //总库存
        $data['number'] = Db::name('wh_stock')->where($where)->sum('number');
        //出库量
        $data['out_number'] = Db::name('wh_stock')->where($where)->sum('out_number');
        //入库量
        $data['join_number'] = Db::name('wh_stock')->where($where)->sum('join_number');

        return $data;
    }

    // 统计盘存信息
    public static function getTakeStat($val = null,$field = 'stock_sn',$condition = 'eq',$map = [],$time = []){
        $where[] = [$field,$condition,$val];
        if(!empty($map))$where = $map;
        //默认上月时间
        if(empty($time[0]))$time[0] = strtotime(date('Y-m-01'),(mktime(0,0,0,date('m'),1,date('Y'))-1));
        if(empty($time[1]))$time[1] = mktime(0,0,0,date('m'),1,date('Y'))-1;
        $time_where[] = ['create_time','BETWEEN',"{$time[0]},$time[1]"];

        //盘前数量
        $data['old_number'] = Db::name('wh_stock_take_log')->where($where)->sum('old_number');
        //盘后数量
        $data['new_number'] = Db::name('wh_stock_take_log')->where($where)->sum('number');
        //盘存损耗
        $data['loss_number'] = Db::name('wh_stock_take_log')->where($where)->sum('loss_number');

        //上期盘前数量
        $data['prev_old_number'] = Db::name('wh_stock_take_log')->where($where)->where($time_where)->sum('old_number');
        //上期盘后数量
        $data['prev_new_number'] = Db::name('wh_stock_take_log')->where($where)->where($time_where)->sum('number');
        //上期盘存损耗
        $data['prev_loss_number'] = Db::name('wh_stock_take_log')->where($where)->where($time_where)->sum('loss_number');

        return $data;
    }

    //打印条形码
    public static function codePrint($pram = [],$width = '100mm',$height = '80mm',$style='',$code = 1){

        $print = isset($pram['print'])?$pram['print']:0;
        $where = [];
        $data = ['msg'=>'','html'=>''];

        if(!empty($pram['stock_sn']))$where[] = ['ms.stock_sn','=',$pram['stock_sn']];
        if(!empty($pram['ids']))$where[] = ['ms.id','in',$pram['ids']];
        if(!empty($pram['material_id'])){

            $stock_sns = Db::name('wh_material_goods')->where(['material_id'=>$pram['material_id']])->column('stock_sn');
            //更新打印状态
            Db::name('wh_material')->where(['id'=>$pram['material_id']])->update(['code_print_status'=>1]);
            $where[] = ['ms.stock_sn','in',implode(',',$stock_sns)];
        }

        if(empty($where))$data['msg'] = '暂无条形码';
        else{
            $list = Db::name('wh_stock')
                ->alias('ms')
                ->field('ms.*,t.title as type_pname,tt.title as type_name,tt2.title as type_name2,tt3.title as type_name3,s.title_abb as supplier_name')
                ->leftJoin('wh_stock_type t','t.id=ms.type_pid')
                ->leftJoin('wh_stock_type tt','tt.id=ms.type_id')
                ->leftJoin('wh_stock_type tt2','tt2.id=ms.type_id2')
                ->leftJoin('wh_stock_type tt3','tt3.id=ms.type_id3')
                ->leftJoin('wh_supplier s','s.id=ms.supplier_id')
                ->where($where)
                ->group('ms.stock_sn')
                ->order('ms.id desc')
                ->select();

            //$html = '<html><head></head><body style="'.$body.'">';
            $html = '<html><head></head><body style="margin: 0;margin-left: 2px;">';

            if(!empty($list[0])){
                $i = count($list);
                foreach ($list as $k=>$v){

                    if(!empty($v['type_name2']))$v['type_name'] = "{$v['type_name2']}";
                    if(!empty($v['type_name3']))$v['type_name'] .= ">{$v['type_name3']}";
                    if(empty($v['title']))$v['title'] = '&nbsp;';
                    $barcode = '<img style="width: 42mm;transform: rotate(-90deg) translateY(-40%) translateX(-20%); " src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/onload.gif" class="barcode" data-val="'.$v['stock_sn'].'">';

                    //按物料分类，拼接内容
                    $arr_html = '';
                    $arr = [
                        '供应商:20|7'       =>  $v['supplier_name'],
                        '名称:20|7'         =>  $v['title'],
                        '规格:20|7'         =>  $v['model'],
                    ];
                    $barcode_colspan = 1;
                    $barcode_rowspan = count($arr)+1;

                    if(in_array($v['type_pid'],ColorModel::$type_pid_arr)){
                        $arr = [
                            '供应商:20|7'       =>  $v['supplier_name'],
                            '颜色名称:20|7'     =>  $v['title'],
                            ':33|13'         =>  $v['model'],
                        ];
                        $barcode_rowspan = count($arr);
                    }
                    elseif ($v['type_pid'] == 4){
                        $arr['批号:20|13'] = $v['lot_sn'];
                    }
                    foreach ($arr as $ak=>$av){
                        $ak = explode(':',$ak);
                        if(empty($ak[1]))$ak[1] = 20;
                        if(!empty($ak[0])){
                            $ak[0] .= '：';
                        }
                        $colrow = explode('|',$ak[1]);
                        $ak[1] = $colrow[0];
                        $colspan = !empty($colrow[1])?$colrow[1]:7;
                        $rowspan = !empty($colrow[2])?$colrow[2]:1;
                        $arr_html .= '<tr style=""><th colspan="'.$colspan.'" rowspan="'.$rowspan.'" style="word-break: break-all;font-size: '.$ak[1].'px;font-weight: 900;">'.$ak[0].$av.'</th></tr>';
                    }

                    $barcode_html = '<th colspan="'.$barcode_colspan.'" rowspan="'.$barcode_rowspan.'" style="width: 100px;height: 40mm;"><div style="width: 100px;height: 40mm;">'.$barcode.'</div></th>';
                    $barcode_html2 = '';
                    if($code == 2)$barcode_html2 = $barcode_html;

                    $margin = 'margin-bottom: 12px;';
                    //$width = '100mm';
                    //$height = '80mm';
                    if($i == $k+1)$margin = '';
                    $html .= '<table border="1" style="border-collapse: collapse;text-align: left;width: '.$width.';height: '.$height.';'.$margin.$style.'">
<tbody>
<tr style="">'.$barcode_html.'<th colspan="7" style="font-size: 20px;font-weight: 900;">类别：'.$v['type_pname'].'>'.$v['type_name'].'</th>'.$barcode_html2.'</tr>
'.$arr_html.'

</tbody>
</table>';
                }
            }
            if($html){
                if($print == 1)$print = 'window.print();';
                else $print = '';
                $html .= '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script><script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script><script type="text/javascript">
                $(function(){
                
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{height:61,margin:5,fontOptions:"bold",fontSize:24,displayValue:true});
                    });
                    //调用打印功能
                    '.$print.'
                    
                });
            </script>';
            }

            $html .= '</body></html>';

            $data['html'] = $html;
        }

        return $data;
    }
}
